/*
crsconverter.ado

This Stata program converts coordinates from one coordinate reference system (CRS) to another using the GeoTools library.

Usage:
    crsconverter x y, gen(new) from("EPSG:sourceCRS") to("EPSG:targetCRS")

Arguments:
    varlist: Two numeric variables representing the x and y coordinates to be converted.
    gen: Prefix for the new variables that will store the converted coordinates.
    from: The EPSG code of the source CRS.
    to: The EPSG code of the target CRS.

Example:
    clear
    set obs 200
    gen double x = 13519436.414
    gen double y = 4859621.225
    crsconverter x y, gen(new) from("EPSG:3857") to("EPSG:2381")

Dependencies:
    - gt-main-32.0.jar
    - gt-referencing-32.0.jar
    - gt-epsg-hsql-32.0.jar
    - gt-epsg-extension-32.0.jar

The program checks for the required GeoTools JAR files and initializes the Java environment if necessary.

Java Method:
    crsconverter(String x, String y, String newx, String newy, String sourceCRS, String targetCRS)
    - Converts coordinates from sourceCRS to targetCRS.
    - Uses GeoTools library for CRS transformation.
    - Optimized for performance by reusing objects and minimizing memory allocation.

Error Handling:
    - Errors during the conversion process are logged with the observation number.
    - If any required JAR file is missing, an error message is displayed and the program exits.

*/


/*

clear
set obs 200
gen double x = 13519436.414
gen double y = 4859621.225
crsconverter x y, gen(new) from("EPSG:3857") to("EPSG:2381")


*/

cap program drop crsconvert
program define crsconvert
version 18

checkdependencies
crsconvert_core `0'

end

program define checkdependencies

version 18 

cap findfile gt-main-32.0.jar
if _rc==0 cap findfile gt-referencing-32.0.jar
if _rc==0 cap findfile gt-epsg-hsql-32.0.jar
if _rc==0 cap findfile gt-epsg-extension-32.0.jar

if _rc{
    cap findfile path_geotoolsjar.ado 
    if _rc {
        di as error "jar path NOT specified, help geotools_init for setting up"
        exit
        
    }

    path_geotoolsjar
    local path `r(path)'
	local jars gt-main-32.0.jar gt-referencing-32.0.jar  gt-epsg-hsql-32.0.jar gt-epsg-extension-32.0.jar

	foreach jar in `jars' {
	
	    cap findfile `jar', path(`"`path'"')
	    if _rc {
        di as error "`jar' NOT found"
        di as error "use geotools_init for re-initializing Java environment"
        di as error "make sure `jar' exists in your specified directory"
        exit
      }
	
	}
	

    qui adopath ++ `"`path'"'

}

end

